// preload.js
const { contextBridge, ipcRenderer } = require('electron');

const fs = require('fs');
const path = require('path');


contextBridge.exposeInMainWorld('electron', {
    getJSON,
    setJSON
});



function getJSON(filePath) {
    
    filePath = path.join(__dirname, filePath)
    console.log('filePath',filePath)
    try {
        const fileContent = fs.readFileSync(filePath, 'utf8');
        const jsonObject = JSON.parse(fileContent);
        return Promise.resolve({ success: true, data: jsonObject });
    } catch (error) {
        return Promise.reject({ success: false, msg: error.message });
    }

}


// 写入JSON文件
function setJSON(filePath, jsonObject) {
    filePath = path.join(__dirname, filePath)
    try {
        const jsonString = JSON.stringify(jsonObject, null, 2); // 格式化JSON字符串，缩进2个空格
        fs.writeFileSync(filePath, jsonString, 'utf8');
        return Promise.resolve({ success: true });
    } catch (error) {
        return Promise.reject({ success: false, msg: error.message });
    }
}




// // 读取JSON文件
// function getJSON(url) {
//     return ipcRenderer.invoke('getJSON', url).then((response) => {
//         if (response.success) {
//             console.log('JSON data:', response.data);
//             return response
//         } else {
//             console.error('Error reading JSON file:', response.msg);
//             return Promise.reject(response)
//         }
//     });
// }



// // 写入JSON文件
// function setJSON(url, content) {
//     return ipcRenderer.invoke('setJSON', url, content).then((response) => {
//         if (response.success) {
//             console.log('JSON file written successfully');
//             return response
//         } else {
//             console.error('Error writing JSON file:', response.msg);
//             return Promise.reject(response)
//         }
//     });
// }